<?php

namespace App\Http\Controllers\OtherSystem;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Controller;
use Log;

class VoiceController extends Controller
{


    public function getToken(){
        $client_id = 'zNqwrhfFDeHfNcuLrZGaiy5R';
        $client_secret = 'Iv4kL3FfDGPhex8eSftjYeMS92QoChZI';
        $auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$client_id."&client_secret=".$client_secret;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $auth_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        $response = json_decode($response, true);
        $token = $response['access_token'];
        return $token;
    }

    public function getVoice(Request $request){
        $url = 'http://tsn.baidu.com/text2audio';
        $tex = urlencode(urlencode($request->tex));
        $lan = urlencode(urlencode('zh'));
        $tok = urlencode(urlencode($this->getToken()));
        $ctp = 1;
        $cuid = urlencode(urlencode('14653858'));
        $spd = urlencode(urlencode($request->spd));
        $vol = urlencode(urlencode($request->vol));
        $pit = urlencode(urlencode($request->pit));
        $per = urlencode(urlencode($request->per));
        $body = 'tex='.$tex.'&lan='.$lan.'&tok='.$tok.'&ctp='.$ctp.'&cuid='.$cuid.'&spd='.$spd.'&vol='.$vol.'&pit='.$pit.'&per='.$per;
        $content_len = "Content-Length: ".strlen($body);
        $header = array ($content_len, 'Content-Type: application/json; charset=utf-8');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
//        $myfile = fopen('newfile.mp3', 'w') ;
//        fwrite($myfile, $response);
//        fclose($myfile);
        $file_name = md5(time()).'.mp3';
        Storage::put('/public/'.$file_name, $response);
        return $file_name;
    }
}
